home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: Sat, 20 Jan 96 01:05:12 GMT
- Organization: none
- Message-ID: <822099912snz@genesis.demon.co.uk>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca> <4dorr8$i58@cloner3.netcom.com> <ALUN.CHAMPION.96Jan19170141@g7240065.bridge.bst.bls.com> <4dp8cr$sit@crl.crl.com>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <4dp8cr$sit@crl.crl.com> bobfry@crl.com "Robert Fry" writes:
-
- >Someone was asking for a quick way to determine if a number is a power of
- >2. The solutions I've seen involved ounting every bit and seeing if the
- >number of 'on' bits is 1. But why not take advantage of the binary
- >representation of numbers and use:
- >
- >int is_power_of_2( long num)
-
- Bill said he was using unsigned long ints which are better suited to this
- (it doesn't work when num is negative).
-
- >{
- > return((( num - 1) & num) == 0);
- >}
-
- It is also important to consider the special case of 0. This classes it
- as a power of 2 which may or may not be what is wanted (or it may not
- matter).
-
- >(You could also make a macro of it if you need better speed in exchange
- >for reduced maintainability):
- >
- >#define IS_POWER_OF_2(num) (!(( num - 1) & num))
-
- Best to fully parenthesize the macro arguments i.e.
-
- #define IS_POWER_OF_2(num) (!((num)-1 & (num)))
-
- >Be careful with this, of course. IS_POWER_OF_2(x++) has undefined results,
- >for example.
-
- Right. Naming conventions have been regularly discussed on comp.lang.c.
- Maybe it would be a good idea to adopt a naming convention which
- clearly distinhuishes macros that are unsafe for side-effects.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-